﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AutoMapper;

namespace Bowerbird.Core.Utils
{
    /// <summary>
    /// Handle convertions between Entities and Dtos
    /// </summary>
    /// <typeparam name="TEntity">The type of the entity.</typeparam>
    /// <typeparam name="TDto">The type of the dto.</typeparam>
    public static class Assembler<TEntity, TDto>
        where TEntity : class
        where TDto : class
    {


        /// <summary>
        /// Initializes the <see cref="Assembler&lt;TEntity, TDto&gt;"/> class.
        /// </summary>
        static Assembler()
        {
            if (typeof(TEntity).GetFields().Any(f => f.Name == "Id"))
                Mapper.CreateMap<TDto, TEntity>().ForMember("Id", a => a.Ignore());
            else
                Mapper.CreateMap<TDto, TEntity>();

            Mapper.CreateMap<TEntity, TDto>();
        }

        /// <summary>
        /// Converts a dto to entity.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <returns></returns>
        public static TEntity ToEntity(TDto source)
        {
            return Mapper.Map<TDto, TEntity>(source);
        }

        /// <summary>
        /// Converts a dto to entity.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="destination">The destination.</param>
        /// <returns></returns>
        public static TEntity ToEntity(TDto source, TEntity destination)
        {
            return Mapper.Map<TDto, TEntity>(source, destination);
        }

        /// <summary>
        /// Converts an entity to dto.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <returns></returns>
        public static TDto ToDto(TEntity source)
        {
            return Mapper.Map<TEntity, TDto>(source);
        }

        /// <summary>
        /// Converts a list of entities to dtos.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <returns></returns>
        public static IEnumerable<TDto> ToDto(IEnumerable<TEntity> source)
        {
            return Mapper.Map<IEnumerable<TEntity>, IEnumerable<TDto>>(source);
        }

        /// <summary>
        /// Converts an entity to dto.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="destination">The destination.</param>
        /// <returns></returns>
        public static TDto ToDto(TEntity source, TDto destination)
        {
            return Mapper.Map<TEntity, TDto>(source, destination);
        }

    }

}
